<template>
	<view>
		<view class="review-container" v-show="reviewAuth">
			<image src="../../static/workbench/review.png" mode="widthFix"></image>
			<view class="title">您的实名资料正在审核中</view>
			<view class="desc">这期间您将无法接单，请等待资料审核通过</view>
		</view>
		<view v-show="!reviewAuth">
			<view class="top-container">
				<view class="notice">今日数据：凌晨00:00 ~ 本日23:59</view>
				<view class="summary-container">
					<view class="item">
						<view class="title">驾驶时长</view>
						<view class="value">
							<text class="number">{{ hour }}</text>
							<text class="unit">时</text>
						</view>
					</view>
					<view class="item">
						<view class="title">今日收入</view>
						<view class="value">
							<text class="number">{{ income }}</text>
							<text class="unit">元</text>
						</view>
					</view>
					<view class="item">
						<view class="title">今日成单</view>
						<view class="value">
							<text class="number">{{ orders }}</text>
							<text class="unit">单</text>
						</view>
					</view>
				</view>
				<view class="service-container">
					<view class="item" :style="service.locationStyle">
						<image :src="service.locationIcon" mode="widthFix" class="icon icon-1"></image>
						{{ service.locationText }}
					</view>
					<view class="item" :style="service.messageStyle">
						<image :src="service.messageIcon" mode="widthFix" class="icon icon-2"></image>
						{{ service.messageText }}
					</view>
					<view class="item" :style="service.listenStyle" @tap="listenHandle()">
						<image :src="service.listenIcon" mode="widthFix" class="icon icon-3"></image>
						{{ service.listenText }}
					</view>
					<view class="item" :style="service.settingStyle" @tap="settingHandle()">
						<image :src="service.settingIcon" mode="widthFix" class="icon icon-4"></image>
						{{ service.settingText }}
					</view>
				</view>
			</view>
			<view v-show="workStatus == '停止接单'">
				<map id="map" :longitude="longitude" :latitude="latitude" scale="15" :style="contentStyle"
					:enable-traffic="true" :show-location="true" :enable-poi="true">
					<cover-image class="location" src="../../static/workbench/location.png"
						@tap="returnLocationHandle()"></cover-image>
				</map>
			</view>
			<scroll-view v-show="workStatus == '开始接单'" scroll-y="true" :style="contentStyle">
				<view class="new-order">
					<view v-if="newOrder == null">
						<image src="../../static/workbench/no-order.png" mode="widthFix" class="no-order-img"></image>
						<view class="no-order-title">目前暂无订单</view>
					</view>
					<view v-else>
						<view class="line-1">
							<view>
								<view class="sub-time">距离您</view>
								<view>
									<text class="number">{{ newOrder.distance }}</text>
									<text class="unit">公里</text>
								</view>
							</view>
							<view>
								<view class="sub-time">全程</view>
								<view>
									<text class="number">{{ newOrder.mileage }}</text>
									<text class="unit">公里</text>
								</view>
							</view>
							<view>
								<view class="tag">含加价{{ newOrder.favourFee }}元</view>
								<view>
									<text class="number">{{ newOrder.expectsFee }}</text>
									<text class="unit">元</text>
								</view>
							</view>
						</view>
						<view class="line-2">
							<view class="from">
								<text>{{ newOrder.from }}</text>
							</view>
							<view class="dashed-line"></view>
							<view class="to">
								<text>{{ newOrder.to }}</text>
							</view>
						</view>
						<button :class="!canAcceptOrder ? 'disabled-btn' : 'accept-btn'"
							@tap="acceptHandle">立即抢单
						</button>
					</view>
				</view>
				<view class="notice-container">
					<view class="title">【 抢单说明 】</view>
					<view class="desc">
						<text class="num">1.</text>
						当前地区可能存在多个打车订单，但是司机端只能显示其中一条订单。这是为了保障乘客订单的接单率，避免司机只挑选优质订单。
					</view>
					<view class="desc">
						<text class="num">2.</text>
						某条订单如果10秒钟之内您没有抢单，系统则认定您主动放弃该订单，系统将为你推送新的订单。
					</view>
				</view>
			</scroll-view>
			<scroll-view scroll-y="true" :style="contentStyle" class="execute-order-container"
				v-show="['接客户', '到达接客点', '开始行程'].includes(workStatus)">
				<view class="call" @tap="callHandle(executeOrder.tel)"></view>
				<view class="customer-container">
					<u-avatar :src="executeOrder.photo" mode="square"></u-avatar>
					<view class="info">
						<view class="customer-name">{{ executeOrder.title }}</view>
						<view class="customer-tel">Tel：{{ executeOrder.tel }}</view>
					</view>
				</view>
				<view class="address-container">
					<view class="from">
						<text>{{ executeOrder.startPlace }}</text>
					</view>
					<view class="dashed-line"></view>
					<view class="to">
						<text>{{ executeOrder.endPlace }}</text>
					</view>
				</view>
				<view class="order-container">
					<view>【 订单号码 】 {{ executeOrder.id }}</view>
					<view>【 下单时间 】 {{ executeOrder.createTime }}</view>
					<view>【 客户红包 】 {{ executeOrder.favourFee }}元</view>
					<!--
					<view>【 驾驶车型 】 {{ executeOrder.carType }}</view>
					<view>【 车辆车牌 】 {{ executeOrder.carPlate }}</view>
					-->
				</view>
				<view class="operate-container">
					<view class="item" @tap="cancelOrderHandle">
						<image src="../../static/workbench/cancel-icon.png" mode="widthFix" class="cancel-icon"></image>
						<text class="cancel-text">取消订单</text>
					</view>
					<view class="vline"></view>
					<view class="item" v-show="workStatus == '接客户'" @tap="arriveStartPlaceHandle">
						<image src="../../static/workbench/arrive-start-icon.png" mode="widthFix"
							class="arrive-start-icon"></image>
						<text class="arrive-start-text">到达接客点</text>
					</view>
					<view class="item" v-show="workStatus == '到达接客点'" @tap="startDrivingHandle">
						<image src="../../static/workbench/drive-start-icon.png" mode="widthFix"
							class="drive-start-icon"></image>
						<text class="drive-start-text">开始驾驶</text>
					</view>
					<view class="item" v-show="workStatus == '开始行程'" @tap="endDrivingHandle">
						<image src="../../static/workbench/drive-stop-icon.png" mode="widthFix" class="drive-stop-icon">
						</image>
						<text class="drive-stop-text">到达终点</text>
					</view>
					<view class="vline"></view>
					<view class="item">
						<image src="../../static/workbench/alarm-icon.png" mode="widthFix" class="alarm-icon"></image>
						<text class="alarm-text">立即报警</text>
					</view>
				</view>
				<view class="other-container">
					<view class="item" @tap="showNavigationHandle">
						<image src="../../static/workbench/other-icon-1.png" mode="widthFix" class="location-icon"></image>
						<text class="location-text">定位导航</text>
					</view>
					<view class="item" @tap="showMoveHandle">
						<image src="../../static/workbench/other-icon-2.png" mode="widthFix" class="display-icon"></image>
						<text class="display-text">司乘同显</text>
					</view>
					<view class="item" @tap="showOrderHandle">
						<image src="../../static/workbench/other-icon-3.png" mode="widthFix" class="order-icon"></image>
						<text class="order-text">订单详情</text>
					</view>
					<view class="item" @tap="callHandle('10001')">
						<image src="../../static/workbench/other-icon-4.png" mode="widthFix" class="service-icon"></image>
						<text class="service-text">客服热线</text>
					</view>
				</view>
			</scroll-view>
			<view class="bottom-container" v-show="['开始接单', '停止接单'].includes(workStatus)">
				<view class="btn" @tap="gohomeHandle()">
					<image src="../../static/workbench/btn-icon-1.png" mode="widthFix" class="btn-icon-1"></image>
					<text>回家</text>
				</view>
				<view class="btn primary">
					<text v-show="workStatus == '停止接单'" @tap="startWorkHandle()">开始接单</text>
					<text v-show="workStatus == '开始接单' || workStat=='结束行程'" @tap="stopWorkHandle()">停止接单</text>
				</view>
				<view class="btn" @tap="toPage('../../wallet/recharge/recharge')">
					<image src="../../static/workbench/btn-icon-2.png" mode="widthFix" class="btn-icon-2"></image>
					<text>充值</text>
				</view>
			</view>
		</view>
		<u-top-tips ref="uTips"></u-top-tips>
		<u-toast ref="uToast" />
		<u-modal v-model="model.cancelConfirm.show" :title="model.cancelConfirm.title"
			:content="model.cancelConfirm.content" :show-confirm-button="true" :show-cancel-button="true"
			@confirm="confirmCancelOrder"></u-modal>
		<u-modal v-model="model.cancelSuccess.show" :title="model.cancelSuccess.title"
			:content="model.cancelSuccess.content" :show-confirm-button="true" :show-cancel-button="false"></u-modal>
	</view>
</template>

<script>
	const chooseLocation = requirePlugin('chooseLocation');
	let plugin = requirePlugin('WechatSI');
	let dayjs = require('dayjs');
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
	let qqmapsdk;
	export default {
		data() {
			return {
				judgeDistance: 0,
				home: undefined,
				acceptOrderAddress: '去选择',
				acceptSettingShow: false,
				reviewAuth: uni.getStorageSync('realAuth') == 3,
				hour: 0,
				income: 0,
				orders: 0,
				map: null,
				windowHeight: 0,
				contentStyle: '',
				latitude: 0,
				longitude: 0,
				service: {
					locationIcon: '../../static/workbench/service-icon-1.png',
					locationText: '定位正常',
					locationStyle: '',
					messageIcon: '../../static/workbench/service-icon-2.png',
					messageText: '推送正常',
					messageStyle: '',
					listenIcon: '../../static/workbench/service-icon-3.png',
					listenText: '收听订单',
					listenStyle: '',
					settingIcon: '../../static/workbench/service-icon-4.png',
					settingText: '接单设置',
					settingStyle: ''
				},
				settings: {
					listenService: true,
					autoAccept: false,
					orientation: '',
					orderDistance: 0,
					rangeDistance: 5
				},
				workStatus: uni.getStorageSync('workStatus'),
				newOrder: null,
				newOrderList: [],
				executeOrder: {
					id: '',
					photo: '',
					title: '',
					tel: '',
					customerId: '',
					startPlace: '',
					startPlaceLocation: {},
					endPlace: '',
					endPlaceLocation: {},
					favourFee: '',
					carPlate: '',
					carType: '',
					createTime: ''
				},
				reciveNewOrderTimer: null,
				playFlag: false,
				audio: null,
				canAcceptOrder: false,
				accepting: false,
				showModel: false,
				modelTitle: '',
				modelContent: '',
				model: {
					cancelConfirm: {
						show: false,
						title: '提示消息',
						content: '如果不满足订单免费取消规则，只能有偿取消订单，并且可能被禁止接单一段时间，您确认要取消当前订单？'
					},
					cancelSuccess: {
						show: false,
						title: '提示消息',
						content: ''
					}
				},
				recordNum: 0,
				recordManager: null,
				stopRecord: false,
				qqmapsdk: null
			};
		},
		methods: {
			gohomeHandle(){
				let that = this;
				//打开手机导航软件
				if(that.home) {
					that.map.openMapApp({
					    latitude: that.home.latitude,
					    longitude: that.home.longitude,
					    destination: that.home.place
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: "未设置回家地址！"
					})
				}
			},
			settingHandle:function() {
				this.toPage("../../user/settings/settings");
			},
			listenHandle:function() {
				let that = this;
				let content = "是否"+ (that.settings.listenService?"关闭":"开启") +"语音播报订单";
				uni.showModal({
					title:"语音播报订单设置",
					content: content,
					success(resp) {
						if(resp.confirm) {
							let data = JSON.parse(JSON.stringify(that.settings));
							data.listenService = !data.listenService;
							that.ajax(that.url.updateDriverSettings, 'POST', data, function(res){
								if(res.data.rows == 1) {
									that.settings = data;
									uni.setStorageSync('settings', that.settings);
									let title = (that.settings.listenService?"开启":"关闭") + "成功";
									uni.showToast({
										icon: 'none',
										title: title
									});
									//更新是否收听订单UI图标
									if (that.settings.listenService) {
										that.service.listenIcon = '../../static/workbench/service-icon-3.png';
										that.service.listenStyle = 'color:#46B68F';
										that.service.listenText = '收听订单';
									} else {
										that.service.listenIcon = '../../static/workbench/service-icon-7.png';
										that.service.listenStyle = 'color:#FF4D4D';
										that.service.listenText = '不听订单';
									}
								}
							})
						}
					}
				})
			},
			endDrivingHandle: function() {
			    let that = this;
			    uni.showModal({
			        title: '消息通知',
			        content: '已经到达终点，现在结束行程？',
			        success: function(resp) {
			            if (resp.confirm) {
							qqmapsdk.calculateDistance({
								mode: 'straight',
								from: {
									latitude: that.latitude,
									longitude: that.longitude
								},
								to: [
									{
										latitude: that.executeOrder.endPlaceLocation.latitude,
										longitude: that.executeOrder.endPlaceLocation.longitude
									}
								],
								success: function(resp) {
									let distance = resp.result.elements[0].distance;
									if (distance <= 2000 || that.judgeDistance > 2) {
										that.judgeDistance = 0;
										let data = {
										    orderId: that.executeOrder.id,
										    customerId: that.executeOrder.customerId,
										    status: 5
										};
										that.ajax(that.url.updateOrderStatus, 'POST', data, function(resp) {
										    that.stopRecord = true;
										    try {
										        that.recordManager.stop(); //停止录音
										        that.recordNum = 0;
										        that.stopRecord = false;
										        that.workStatus = '结束行程';
										        uni.setStorageSync('workStatus', '结束行程');
										        //页面发生跳转
										        uni.navigateTo({
										            url: '../../order/enter_fee/enter_fee?orderId=' + that.executeOrder.id + '&customerId=' + that.executeOrder.customerId
										        });
										    } catch (e) {
										        console.error(e);
										    }
										});
									} else {
										uni.showToast({
											icon: 'none',
											title: '请移动到距离行程终点2公里以内'
										});
										that.judgeDistance++;
									}
								},
								fail: function(error) {
									console.log(error);
								}
							});
			            }
			        }
			    });
			},
			showNavigationHandle: function() {
			    let that = this;
			    let latitude = null;
			    let longitude = null;
			    let destination = null;
			    if (that.workStatus == '接客户') {
			        latitude = Number(that.executeOrder.startPlaceLocation.latitude);
			        longitude = Number(that.executeOrder.startPlaceLocation.longitude);
			        destination = that.executeOrder.startPlace;
			    } else {
			        latitude = Number(that.executeOrder.endPlaceLocation.latitude);
			        longitude = Number(that.executeOrder.endPlaceLocation.longitude);
			        destination = that.executeOrder.endPlace;
			    }
			    //打开手机导航软件
			    that.map.openMapApp({
			        latitude: latitude,
			        longitude: longitude,
			        destination: destination
			    });
			},
			startDrivingHandle: function() {
			    let that = this;
			    uni.showModal({
			        title: '消息通知',
			        content: '您已经接到客户，现在开始行程？',
			        success: function(resp) {
			            if (resp.confirm) {
			                //TODO 设置录音标志位
			                let data = {
			                    orderId: that.executeOrder.id,
			                    customerId: that.executeOrder.customerId
			                };
			
			                that.ajax(that.url.startDriving, 'POST', data, function(resp) {
			                    if (resp.data.rows == 1) {
			                        uni.showToast({
			                            icon: 'success',
			                            title: '订单状态更新成功，开始驾驶'
			                        });
			                        that.workStatus = '开始行程';
			                        uni.setStorageSync('workStatus', '开始行程');
			                        //开始录音
			                        that.recordManager.start({ duration: 20 * 1000, lang: 'zh_CN' });
			                    } else {
									uni.showToast({
									    icon: 'none',
									    title: '开始失败,乘客未确认您到达起点!'
									});
								}
			                });
			            }
			        }
			    });
			},
			arriveStartPlaceHandle: function() {
			    let that = this;
			    uni.showModal({
			        title: '消息通知',
			        content: '确认已经到达了接送点？',
			        success: function(resp) {
			            if (resp.confirm) {
			                qqmapsdk.calculateDistance({
								mode: 'straight',
								from: {
									latitude: that.latitude,
									longitude: that.longitude
								},
								to: [
									{
										latitude: that.executeOrder.startPlaceLocation.latitude,
										longitude: that.executeOrder.startPlaceLocation.longitude
									}
								],
								success: function(resp) {
									let distance = resp.result.elements[0].distance;
									if (distance <= 1000) {
										let data = {
											orderId: that.executeOrder.id,
											customerId: that.executeOrder.customerId
										};
										that.ajax(that.url.arriveStartPlace, 'POST', data, function(resp) {
											if (resp.data.rows == 1) {
												uni.showToast({
													icon: 'none',
													title: '订单状态更新成功'
												});
												that.workStatus = '到达接客点';
												uni.setStorageSync('workStatus', '到达接客点');
											}
										});
									} else {
										uni.showToast({
											icon: 'error',
											title: '请移动到距离行程起点1公里以内'
										});
									}
								},
								fail: function(error) {
									console.log(error);
								}
							});
			            }
			        }
			    });
			},
			showMoveHandle: function() {
			    let that = this;
			    uni.navigateTo({
			        url: `../../execution/move/move?orderId=` + that.executeOrder.id
			    });
			},
			callHandle: function(telNumber) {
			    uni.makePhoneCall({
			        phoneNumber: telNumber
			    });
			},
			loadExecuteOrder: function() {
				let ref = this;
			    ref.ajax(ref.url.searchDriverExecuteOrder, 'POST', { orderId: ref.executeOrder.id }, function(resp) {
			        let result = resp.data.result;
			        // console.log(result);
			        ref.executeOrder = {
			            id: ref.executeOrder.id,
			            photo: result.photo,
			            title: result.title,
			            tel: result.tel,
			            customerId: result.customerId,
			            startPlace: result.startPlace,
			            startPlaceLocation: JSON.parse(result.startPlaceLocation),
			            endPlace: result.endPlace,
			            endPlaceLocation: JSON.parse(result.endPlaceLocation),
			            favourFee: result.favourFee,
			            carPlate: result.carPlate,
			            carType: result.carType,
			            createTime: result.createTime
			        };
			
			        ref.workStatus = '接客户';
			        uni.setStorageSync('workStatus', '接客户');
			        uni.setStorageSync('executeOrder', ref.executeOrder);
			    });
			},
			acceptHandle: function() {
			    let that = this;
				//避免多次重复抢单
			    if (!that.canAcceptOrder || that.accepting) {
			        return;
			    }
				//标记正在抢单中
			    that.accepting = true; 
			    uni.vibrateShort({});
			    that.ajax(that.url.acceptNewOrder, 'POST', { orderId: that.newOrder.orderId }, function(resp) {
			        let audio = uni.createInnerAudioContext();
			        let result = resp.data.result;
			        //手动抢单成功
			        if (result == '接单成功') {
			            uni.showToast({
			                title: '接单成功'
			            });
			            that.audio = audio;
			            audio.src = '/static/voice/voice_3.mp3';
			            audio.play();
			            audio.onPlay(function() {
			                //停止接单
			                that.audio = null;
			                that.ajax(that.url.stopWork, 'POST', null, function(resp) {});
			
			                //初始化新订单和列表变量
			                that.executeOrder.id = that.newOrder.orderId;
			                that.newOrder = null;
			                that.newOrderList.length = 0;
			                clearInterval(that.reciveNewOrderTimer);
			                that.reciveNewOrderTimer = null;
			                that.playFlag = false;
			                that.accepting = false;
			                that.canAcceptOrder = false;
			                //隐藏了工作台页面底部操作条之后，需要重新计算订单执行View的高度
			                that.contentStyle = `width: 750rpx;height:${that.windowHeight - 200 - 0}px;`;
			                //加载订单执行数据
							that.loadExecuteOrder();
			            });
			        } else {
						uni.showToast({
						    title: '抢单失败' + (that.newOrderList.length > 0?",自动为您加载新订单!":"!"),
							duration: 1000
						});
			            that.audio = audio;
			            audio.src = '/static/voice/voice_4.mp3';
			            audio.play();
			            that.playFlag = false;
			            setTimeout(function() {
			                that.accepting = false;
			                that.canAcceptOrder = false;
			                if (that.newOrderList.length > 0) {
			                    that.showNewOrder(); //递归调用
			                } else {
			                    that.newOrder = null;
			                }
			            }, 3000);
			        }
			    });
			},
			showNewOrder: function() {
				let ref = this;
				ref.playFlag = true;
				ref.canAcceptOrder = false;
				let order = ref.newOrderList.shift();
				let orderId = order.orderId;
				let distance = order.distance;
				let expectsFee = order.expectsFee;
				let favourFee = order.favourFee;
				let from = order.from;
				let to = order.to;
				let mileage = order.mileage;
				let minute = order.minute;
				ref.newOrder = {
					orderId: orderId,
					distance: distance,
					expectsFee: expectsFee,
					favourFee: favourFee,
					from: from,
					to: to,
					mileage: mileage,
					minute: minute
				};
				//是否开启收听订单
				if (ref.settings.listenService) {
					let audio = uni.createInnerAudioContext();
					ref.audio = audio;
					plugin.textToSpeech({
						lang: 'zh_CN',
						tts: true,
						content: `即时订单，距离您${distance}公里，从${from}，到${to}，全程约${mileage}公里，预估行程费${expectsFee}元`,
						success: function(resp) {
							audio.src = resp.filename;
							audio.play();
							audio.onEnded(function() {
								ref.canAcceptOrder = true;
								let verification = uni.getStorageSync('verification');
								/*
								 * TODO 判断人脸识别凭证是否过期，如果过期就要重新人脸验证。
								 * 这是以防司机今天开始接单人脸验证通过，但是一直没有停止接单，
								 * 到了次日依然要重新做人脸验证。
								 *
								 */
								let canStartWork = true;
								// ref.ajax(ref.url.searchCanStartWork, 'GET', {}, function(resp) {
								// 		let result = resp.data.result;
								// 		let faceRecognition = result.faceRecognition;
								// 		let lockdown = result.lockdown;
								// 		let hasFine = result.hasFine;
								// 		if(!faceRecognition || lockdown || hasFine) {
								// 			canStartWork = false;
								// 		}
								// 	}
								// )
								
								if (!canStartWork) {
									
								} else {
									//自动接单
									if (ref.settings.autoAccept) {
										let data = {
											orderId: orderId
										};
										ref.ajax(
											ref.url.acceptNewOrder,
											'POST',
											data,
											function(resp) {
												let result = resp.data.result;
												if (result == '接单成功') {
													uni.showToast({
														title: '接单成功'
													});
													audio = uni.createInnerAudioContext();
													ref.audio = audio;
													audio.src = '/static/voice/voice_3.mp3';
													audio.play();
													audio.onEnded(function() {
														ref.ajax(ref.url.stopWork, 'POST', null, function(resp) {});
														//初始化新订单和列表变量
														ref.newOrder = null;
														ref.newOrderList.length = 0;
														ref.executeOrder.id = orderId;
														clearInterval(ref.reciveNewOrderTimer);
														ref.reciveNewOrderTimer = null;
														ref.playFlag = false;
														//隐藏了工作台页面底部操作条之后，需要重新计算订单执行View的高度
														ref.contentStyle = `width: 750rpx;height:${ref.windowHeight - 200 - 0}px;`;
														//加载订单执行数据
														ref.loadExecuteOrder();
													});
												} else {
													//自动抢单失败
													audio = uni.createInnerAudioContext();
													ref.audio = audio;
													audio.src = '/static/voice/voice_4.mp3';
													audio.play();
													audio.onEnded(function() {
														ref.playFlag = false;
														if (ref.newOrderList.length > 0) {
															ref.showNewOrder();
														} else {
															ref.newOrder = null;
														}
													});
												}
											},
											false
										);
									} else {
										ref.playFlag = false;
										setTimeout(function() {
											//如果用户不是正在手动抢单中，就播放下一个新订单
											if (!ref.accepting) {
												ref.canAcceptOrder = false;
												if (ref.newOrderList.length > 0) {
													ref.showNewOrder(); //递归调用
												} else {
													ref.newOrder = null;
												}
											}
										}, 3000);
									}
								}
							});
						},
						fail: function(resp) {
							console.error('语音订单播报失败', resp);
							ref.playFlag = false;
							ref.canAcceptOrder = true;
							ref.acception = false;
						}
					});
				} else {
					setTimeout(()=>{
						ref.canAcceptOrder = true;
					},3000);
					let verification = uni.getStorageSync('verification');
					let canStartWork = true;
					// ref.ajax(ref.url.searchCanStartWork, 'GET', {}, function(resp) {
					// 		let result = resp.data.result;
					// 		let faceRecognition = result.faceRecognition;
					// 		if(!faceRecognition || lockdown || hasFine) {
					// 			canStartWork = false;
					// 		}
					// 	}
					// )
					
					if (!canStartWork) {
						uni.showModal({
							title: '消息通知',
							content: '您今日还没有进行人脸识别验证，无法接单！',
							cancelText: '我知道了',
							confirmText: '立即验证',
							success: function(resp) {
								if (resp.confirm) {
									uni.navigateTo({
										url: '../../identity/face_camera/face_camera?mode=verificate'
									});
								}
							}
						});
					} else {
						//自动接单
						if (ref.settings.autoAccept) {
							let data = {
								orderId: orderId
							};
							ref.ajax(
								ref.url.acceptNewOrder,
								'POST',
								data,
								function(resp) {
									let result = resp.data.result;
									if (result == '接单成功') {
										uni.showToast({
											title: '接单成功'
										});
										audio = uni.createInnerAudioContext();
										ref.audio = audio;
										audio.src = '/static/voice/voice_3.mp3';
										audio.play();
										audio.onEnded(function() {
											ref.ajax(ref.url.stopWork, 'POST', null, function(resp) {});
											//初始化新订单和列表变量
											ref.newOrder = null;
											ref.newOrderList.length = 0;
											ref.executeOrder.id = orderId;
											clearInterval(ref.reciveNewOrderTimer);
											ref.reciveNewOrderTimer = null;
											ref.playFlag = false;
											//隐藏了工作台页面底部操作条之后，需要重新计算订单执行View的高度
											ref.contentStyle = `width: 750rpx;height:${ref.windowHeight - 200 - 0}px;`;
											//加载订单执行数据
											ref.loadExecuteOrder();
										});
									} else {
										//自动抢单失败
										audio = uni.createInnerAudioContext();
										ref.audio = audio;
										audio.src = '/static/voice/voice_4.mp3';
										audio.play();
										audio.onEnded(function() {
											ref.playFlag = false;
											if (ref.newOrderList.length > 0) {
												ref.showNewOrder();
											} else {
												ref.newOrder = null;
											}
										});
									}
								},
								false
							);
						} else {
							ref.playFlag = false;
							setTimeout(function() {
								//如果用户不是正在手动抢单中，就播放下一个新订单
								if (!ref.accepting) {
									ref.canAcceptOrder = false;
									if (ref.newOrderList.length > 0) {
										ref.showNewOrder(); //递归调用
									} else {
										ref.newOrder = null;
									}
								}
							}, 3000);
						}
					}
				}
			},
			createTimer: function() {
				let ref = this;
				let timer = setInterval(function() {
					ref.ajax(
						ref.url.receiveNewOrderMessage,
						'POST',
						null,
						function(resp) {
							let result = resp.data.result;
							if (result.length > 0) {
								//用新订单数组和原有订单数组拼接成新数组，新订单就放在数组开头
								ref.newOrderList = result.concat(ref.newOrderList);
								//如果当前没有播报订单，就显示新的订单
								if (ref.playFlag == false) {
									//调用封装函数，播报最新订单
									ref.showNewOrder();
								}
							}
						},
						false
					);
				}, 5000);
				return timer;
			},
			returnLocationHandle: function() {
				let that = this;
				wx.getLocation({
					type: 'wgs84',
					success (res) {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						console.log("获取定位成功:" + that.latitude + " " + that.longitude)
						wx.getSystemInfo({
							success: (res) => {
								console.log('SystemInfo:', res.platform);
								if(res.platform != 'android' && res.platform != 'ios') {
									//解决电脑端不更新定位演示问题
									let location = { latitude: 24.626664, longitude: 118.074079 };
									uni.$emit('updateLocation', location);
								}
							}
						});
					}
				})
				this.map.moveToLocation();
			},
			startWorkHandle: function() {
				let that = this;
				/*
				 * 检查司机是否可以接单
				 * 1.没有被禁止接单
				 * 2.没有未缴纳的罚款
				 * 3.当天已经做了人脸验证
				 */
				let canStartWork = true;
				that.ajax(that.url.searchCanStartWork, 'GET', {}, function(resp) {
						let result = resp.data.result;
						let faceRecognition = result.faceRecognition;
						let lockdown = result.lockdown;
						let hasFine = result.hasFine;
						// if(!faceRecognition || lockdown || hasFine) {
						// 	canStartWork = false;
						// }
						if (!faceRecognition) {
							uni.showModal({
								title: '消息通知',
								content: '您今日还没有进行人脸识别验证，无法接单！',
								cancelText: '我知道了',
								confirmText: '立即验证',
								success: function(resp) {
									if (resp.confirm) {
										uni.navigateTo({
											url: '../../identity/face_camera/face_camera?mode=verificate'
										});
									}
								}
							});
						} else if(lockdown) {
							uni.showToast({
								icon: 'none',
								title: '您已被禁止接单，如有疑问请联系客服！'
							});
						} else if(hasFine) {
							uni.showModal({
								title: '消息通知',
								content: '您还有罚款未支付，无法接单！',
								cancelText: '我知道了',
								confirmText: '立即支付',
								success: function(resp) {
									if (resp.confirm) {
										uni.navigateTo({
											url: '../../user/fine_list/fine_list'
										});
									}
								}
							});
						} else {
							//设置司机当天通过身份验证
							uni.setStorageSync('verification', {
								result: true,
								date: dayjs().format('YYYY-MM-DD')
							});
							
							uni.showModal({
								title: '提示消息',
								content: '是否开始接收订单信息？',
								success: function(resp) {
									if (resp.confirm) {
										uni.vibrateShort({});
										that.$refs.uToast.show({
											title: '开始接单',
											type: 'success',
											callback: function() {
												let settings = uni.getStorageSync('settings');
												let orderDistance = settings.orderDistance;
												let rangeDistance = settings.rangeDistance;
												let orientation = settings.orientation;
												
												//发送开始接单请求给系统
												that.ajax(that.url.startWork, 'POST', 
													{
														latitude: that.latitude,
														longitude: that.longitude,
														orderDistance: orderDistance,
														rangeDistance: rangeDistance,
														orientateLongitude: orientation != '' ? orientation.longitude : null,
														orientateLatitude: orientation != '' ? orientation.latitude : null
													},
													function(resp) {
														//播放接单提示音
														let audio = uni.createInnerAudioContext();
														that.audio = audio;
														audio.src = '/static/voice/voice_1.mp3';
														audio.play();
														uni.setStorageSync('workStatus', '开始接单');
														that.workStatus = '开始接单'; 
														//初始化新订单和列表变量
														that.newOrder = null;
														that.newOrderList.length = 0;
														that.executeOrder = {};
														//创建接收新订单消息的定时器，每隔5秒钟接收一次新订单消息
														if (that.reciveNewOrderTimer == null) {
															that.reciveNewOrderTimer = that.createTimer(that);
														}
													}
												);
												
											}
										});
									}
								}
							});
						}
					}
				)
			},
			stopWorkHandle: function() {
				let that = this;
				uni.showModal({
					title: '提示消息',
					content: '是否停止接收订单信息？',
					success: function(resp) {
						if (resp.confirm) {
							uni.vibrateShort({});
							if (that.audio != null) {
								that.audio.stop();
							}
							let audio = uni.createInnerAudioContext();
							that.audio = audio;
							audio.src = '/static/voice/voice_2.mp3';
							audio.play();
							that.$refs.uToast.show({
								title: '停止接单',
								type: 'default',
								callback: function() {
									//发送停止接单请求给系统
									that.ajax(that.url.stopWork, 'POST', null, function(
										resp) {});
									that.workStatus = '停止接单';
									uni.setStorageSync('workStatus', '停止接单');
									//初始化新订单和列表变量
									that.newOrder = null;
									that.newOrderList.length = 0;
									that.executeOrder = {};
									//销毁定时器
									clearInterval(that.reciveNewOrderTimer);
									that.reciveNewOrderTimer = null;
									that.playFlag = false;
								}
							});
						}
					}
				});
			}
		},
		onLoad: function() {
			let that = this;
			that.windowHeight = uni.getSystemInfoSync().windowHeight;
			qqmapsdk = new QQMapWX({
				key: that.tencent.map.key
			});
			if (!that.reviewAuth) {
				let recordManager = plugin.getRecordRecognitionManager(); //初始化录音管理器
				//录音停止监听器
				recordManager.onStop = function(resp) {
					if (that.workStatus == '开始行程' && that.stopRecord == false) {
						//每20秒录音一次上传
						that.recordManager.start({ duration: 20 * 1000, lang: 'zh_CN' });
					}
	
					let tempFilePath = resp.tempFilePath;
					//上传录音
					that.recordNum += 1;
					let data = {
						name: `${that.executeOrder.id}-${that.recordNum}.mp3`,
						text: resp.result
					};
					//main.js自定义上传函数,封装了uni.uploadFile
					that.upload(that.url.uploadRecordFile, tempFilePath, data, function(resp) {
						console.log('录音上传成功');
					});
				};
				//录音启动监听器
				recordManager.onStart = function(resp) {
					console.log('成功开始录音识别');
					if (that.recordNum == 0) {
						uni.vibrateLong({
							complete: function() {}
						});
						uni.showToast({
							icon: 'none',
							title: '请提示客户系上安全带！'
						});
					}
				};
				//录音失败监听器
				recordManager.onError = function(resp) {
					console.error('录音识别故障', resp.msg);
				};
	
				that.recordManager = recordManager;
			}
			//查询正在执行的订单
			that.ajax(
				that.url.searchDriverCurrentOrder,
				'POST',
				null,
				function(resp) {
					if (resp.data.hasOwnProperty('result')) {
						let result = resp.data.result;
						that.executeOrder = {
							id: result.id,
							photo: result.photo,
							title: result.title,
							tel: result.tel,
							customerId: result.customerId,
							startPlace: result.startPlace,
							startPlaceLocation: JSON.parse(result.startPlaceLocation),
							endPlace: result.endPlace,
							endPlaceLocation: JSON.parse(result.endPlaceLocation),
							favourFee: result.favourFee,
							carPlate: result.carPlate,
							carType: result.carType,
							createTime: result.createTime
						};
						that.contentStyle = `width: 750rpx;height:${that.windowHeight - 200 - 0}px;`;
						let map = {
							'2': '接客户',
							'3': '到达接客点',
							'4': '开始行程'
						};
						that.workStatus = map[result.status + ''];
						uni.setStorageSync('workStatus', that.workStatus);
						uni.setStorageSync('executeOrder', that.executeOrder);
						// console.log(that.workStatus);
						if (that.workStatus == '开始行程') {
							that.recordManager.start({ duration: 20 * 1000, lang: 'zh_CN' });
						}
					}
				},
				false
			);
			//初始化地图
			this.map = uni.createMapContext('map');
		},
		onShow: function() {
			let that = this;
            //更新司机实名审核结果
            that.reviewAuth = uni.getStorageSync('realAuth') == 3;
			//获取一次定位
			that.returnLocationHandle();
			if (!that.reviewAuth) {
				//查询控制台数据
				that.ajax(that.url.searchWorkbenchData, 'POST', null, function(resp) {
					let result = resp.data.result;
					that.hour = result.business.duration;
					that.income = result.business.income;
					that.orders = result.business.orders;
					//存储回家地址
					uni.setStorageSync("home", result.settings.home);
					that.home = JSON.parse(result.settings.home);
					//删除json中home字段
					delete result.settings.home;
					that.settings = result.settings;
					uni.setStorageSync('settings', that.settings);
					//更新是否收听订单UI图标
					if (that.settings.listenService) {
						that.service.listenIcon = '../../static/workbench/service-icon-3.png';
						that.service.listenStyle = 'color:#46B68F';
						that.service.listenText = '收听订单';
					} else {
						that.service.listenIcon = '../../static/workbench/service-icon-7.png';
						that.service.listenStyle = 'color:#FF4D4D';
						that.service.listenText = '不听订单';
					}
					//实时获取定位
					uni.$on('updateLocation', function(location) {
						// console.log(location)
						if (location != null) {
							that.service.locationIcon = '../../static/workbench/service-icon-1.png';
							that.service.locationText = '定位正常';
							that.service.locationStyle = 'color:#46B68F';
							that.latitude = location.latitude;
							that.longitude = location.longitude;
						} else {
							that.service.locationIcon = '../../static/workbench/service-icon-5.png';
							that.service.locationText = '定位失败';
							that.service.locationStyle = 'color:#FF4D4D';
						}
					});
					let workStatus = uni.getStorageSync('workStatus');
					that.workStatus = workStatus;
					//判断工作状态
					if (workStatus == '开始接单') {
						that.newOrder = null;
						that.newOrderList.length = 0;
						that.playFlag = false; 
						//创建接收新订单消息的定时器，每隔5秒钟接收一次新订单消息
						that.reciveNewOrderTimer = that.createTimer();
					}
					//初始化控件高度
					if (['接客户', '到达接客点', '开始行程'].includes(workStatus)) {
						that.contentStyle = `width: 750rpx;height:${that.windowHeight - 200 - 0}px;`;
					} else {
						that.contentStyle = `width: 750rpx;height:${that.windowHeight - 200 - 70}px;`;
					}
				});
			}
		},
		onHide: function() {
			//取消监听位置更新事件
			uni.$off('updateLocation');
			this.newOrder = null;
			this.newOrderList.length = 0;
			if (this.audio != null) {
				this.audio.stop();
				this.audio = null;
			}
			clearInterval(this.reciveNewOrderTimer);
			this.reciveNewOrderTimer = null;
			this.playFlag = false;
		}
	};
</script>

<style lang="less">
	@import url('workbench.less');
</style>
